package view;

import entity.Order;
import entity.Products;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import services.Service;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableColumnModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Vector;

public class AddOrderJFrame extends JFrame implements ActionListener, MouseListener {
    // 定义全局组件
    JPanel backgroundPanel,topPanel,toolPanel,tablePanel, bottomPanel,datePanel,submitPanel ;
    JLabel toolAdd,toolDelete,toolModify,inputLabel, customerLabel;
    JTextField inputDate;
    JComboBox customerJCBox;

    BaseTableModule baseTableModule;
    JTable table;
    JScrollPane jScrollPane;
    JButton buttonAdd;
    Service service;

    Order order; // 订单编号,客户编号,商品编号[],数量[],售价,成交日期
    ArrayList<String> productsIds = new ArrayList<>();
    ArrayList<Integer> amounts = new ArrayList<>();
    public Map<String,String> customerMap = null;

    // 父面板对象
    OrderJPanel parentPanel;
    // 获得屏幕的大小
    final static int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    final static int height = Toolkit.getDefaultToolkit().getScreenSize().height;

    public AddOrderJFrame(Service service, OrderJPanel orderJPanel) {
        this.service = service;
        this.parentPanel = orderJPanel;

        customerMap = service.selectAllIdName(2);
        order = new Order(""+System.currentTimeMillis(),null,productsIds,amounts,0, new Date());

        initBackgroundPanel();

        this.add(backgroundPanel);

        this.setTitle("添加订单");
        this.setSize((int) (width * 0.7f), (int) (height * 0.7f));
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }

    // 初始化背景面板
    public void initBackgroundPanel() {
        backgroundPanel = new JPanel(new BorderLayout());
        initTopPanel();
        initTablePanel();
        initBottomPanel();
    }

    // 初始化顶部面板
    private void initTopPanel() {
        topPanel = new JPanel(new BorderLayout());

        initToolPanel();

        backgroundPanel.add(topPanel, "North");
    }
    // 初始化工具面板
    public void initToolPanel() {
        toolPanel = new JPanel();
        // 工具图标
        Icon iconAdd = new ImageIcon("image/add.png");
        toolAdd = new JLabel(iconAdd);
        toolAdd.setToolTipText("新建");
        toolAdd.addMouseListener(this);

        Icon iconModify = new ImageIcon("image/modify.png");
        toolModify = new JLabel(iconModify);
        toolModify.setToolTipText("修改");
        toolModify.addMouseListener(this);

        Icon iconDelete = new ImageIcon("image/delete.png");
        toolDelete = new JLabel(iconDelete);
        toolDelete.setToolTipText("删除");
        toolDelete.addMouseListener(this);

        toolPanel.add(toolAdd);
        toolPanel.add(toolModify);
        toolPanel.add(toolDelete);

        topPanel.add(toolPanel, "West");
    }
    // 初始化数据表格面板
    public void initTablePanel() {

        String[] params = { "编号", "名称", "供应商", "库存","成本","售价","入库时间","数量"};
        // 订单编号,客户编号,商品编号[],数量[],售价,成交日期
        Vector<Vector> vector = new Vector<Vector>();
        try {
            System.out.println(productsIds);
            System.out.println(amounts);
            vector = service.selectByIds(0, productsIds, amounts);

            System.out.println(vector);
        } catch (Exception e) {
            e.printStackTrace();
        }

        baseTableModule = new BaseTableModule(params, vector);

        table = new JTable(baseTableModule);
        Tools.setTableStyle(table);
        DefaultTableColumnModel dcm = (DefaultTableColumnModel) table.getColumnModel();// 获取列模型
        dcm.getColumn(0).setMinWidth(0); // 将第一列的最小宽度、最大宽度都设置为0
        dcm.getColumn(0).setMaxWidth(0);
        dcm.getColumn(4).setMinWidth(0); // 将第五列的最小宽度、最大宽度都设置为0
        dcm.getColumn(4).setMaxWidth(0);
        jScrollPane = new JScrollPane(table);
        Tools.setJspStyle(jScrollPane);

        tablePanel = new JPanel(new BorderLayout());
        tablePanel.setOpaque(false);

        tablePanel.add(jScrollPane);

        backgroundPanel.add(tablePanel, "Center");
    }

    // 更新数据表格
    public void refreshTablePanel() {
        backgroundPanel.remove(tablePanel);
        initTablePanel();
        backgroundPanel.validate();
    }

    private void initBottomPanel() {
        bottomPanel = new JPanel(new BorderLayout());
        initInputData();
        initSubmit();
        backgroundPanel.add(bottomPanel, "South");
    }

    private void initInputData() {
        datePanel = new JPanel();
        inputLabel = new JLabel("  日期（yy-MM-dd）:");
        inputDate = new JTextField(10);
        customerLabel = new JLabel("客户：");
        customerJCBox = new JComboBox();
        if (customerMap != null) {
            for (String s : customerMap.keySet()) {
                customerJCBox.addItem(s);
            }
        }

        datePanel.add(inputLabel);
        datePanel.add(inputDate);
        datePanel.add(customerLabel);
        datePanel.add(customerJCBox);
        bottomPanel.add(datePanel,"West");

    }

    private void initSubmit() {
        submitPanel = new JPanel();

        buttonAdd = new JButton("提交");
        buttonAdd.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.lightBlue));
        buttonAdd.setForeground(Color.white);
        buttonAdd.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        buttonAdd.addMouseListener(this);

        submitPanel.add(buttonAdd);

        bottomPanel.add(submitPanel, "East");
    }


    @Override
    public void actionPerformed(ActionEvent e) {

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == buttonAdd) {
            String transactionDate = inputDate.getText().trim();
            String customerString = (String) customerJCBox.getSelectedItem();
            if(customerString == null || customerString.length() == 0){
                JOptionPane.showMessageDialog(null, "请先添加客户");
            }if(order.getProductsIds().size() == 0){
                JOptionPane.showMessageDialog(null, "请添加产品");
            } else if (transactionDate.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请输入日期");
            } else {
                int result = 0;
                try {
                    String customerIdString = customerMap.get(customerString);
                    order.setTransactionDate((new SimpleDateFormat("yy-MM-dd")).parse(transactionDate));
                    order.setCustomerId(customerIdString);
                    result = service.insertById(3, order);
                    Map<String, Products> productsIdMap = service.getProductMap();
                    int i =0;
                    for(String productsId: productsIds){
                       Products products = (Products) productsIdMap.get(productsId);
                       products.setInventory(products.getInventory() - amounts.get(i));
                       order.setPrice(order.getPrice()+amounts.get(i)*products.getPrice());
                       i++;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                if (result > 0) {
                    JOptionPane.showMessageDialog(null, "提交成功");
                    this.setVisible(false);
                    parentPanel.refreshTablePanel();
                }
            }
        }else if (e.getSource() == toolAdd) {
            try {
                new AddOrderProductsJFrame(service, productsIds,amounts, this);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (e.getSource() == toolModify) {
            int row = table.getSelectedRow();
            if (row < 0) {
                JOptionPane.showMessageDialog(null, "请选择客户");
            } else {
                try {
                    new ModifyOrderProductsJFrame(service,productsIds,amounts,this, table, row);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } else if (e.getSource() == toolDelete) {
            int row = table.getSelectedRow();
            if (row < 0) {
                JOptionPane.showMessageDialog(null, "请选择客户");
            } else {
                String id = (String) table.getValueAt(row, 0);
                int result = JOptionPane.showConfirmDialog(null, "是否确定删除？", "用户提示", JOptionPane.YES_NO_OPTION);
                if (result == 0) {
                    try {
                        int tempresult = service.deleteById(2,id);
                        if (tempresult > 0) {
                            JOptionPane.showMessageDialog(null, "删除成功！");
                            refreshTablePanel();
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        if (e.getSource() == toolAdd) {
            toolAdd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        } else if (e.getSource() == toolModify) {
            toolModify.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        } else if (e.getSource() == toolDelete) {
            toolDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
